package uk.co.accolade.clash.core.message;

import uk.co.accolade.clash.core.ClashFilePath;
import uk.co.accolade.clash.core.UserChanges;
import uk.co.accolade.clash.core.Username;

import java.lang.reflect.Field;
import java.util.Arrays;

public class MessageParser_V0 implements MessageParser {

    public String filename;
    public String username;
    
    public UserChanges parse( String message ) {
        DataToken[] tokens = DataToken.tokensFromMessage( message );
        populateDataFields( tokens );
        return instantiateUserChanges();
    }

    private UserChanges instantiateUserChanges() {
        return new UserChanges( new Username(username), Arrays.asList( new ClashFilePath(filename) ) );
    }


    private void populateDataFields( DataToken[] tokens ) {
        for( DataToken token : tokens ) {
            try {
                Field dataField = this.getClass(). getDeclaredField( token.key );
                dataField.set( this, token.value );
            } catch( NoSuchFieldException e ) {
                //do nothing
            } catch( IllegalAccessException e ) {
                throw new ClashEventParseException( "Reflection exception", e );
            }
        }
    }
}